<template>
  <div class="topup page" ref="webview">
    <div class="wrapper">
      <van-nav-bar title="充值" class="bg_white" right-text="充值记录" left-arrow @click-left="$router.push({path: '/my'})" @click-right="$router.push({path: '/topup/detail'})"></van-nav-bar>
      <div class="name">输入充值金额</div>
      <div class="box van-hairline--bottom">
        <span class="symbol">￥</span>
        <div class="input">
          <van-field clickable v-model="rechargeAmount" type="number" :placeholder="'充值T+1到账，最低充值'+minRechargeAmount+'元'" />
        </div>
      </div>
      <div class="info">充值金额区间：{{minRechargeAmount}} - {{maxRechargeAmount}}</div>
      <div class="line"></div>
      <div class="payTitle">付款方式</div>
      <div class="payList">
        <template v-for="(item,index) in payList">
          <div class="rows-item" :key="index" @click="activeIndex=index">
            <span class="radio" :class="{active: activeIndex === index}"></span>
            <span :class="'payName'+' '+item.value">{{item.name}}</span>
          </div>
        </template>
      </div>
      <div class="submitAdd">
        <van-button round color="#125DFF" class="btn" @click="rechargeSecond">立即充值</van-button>
      </div>
    </div>
    <!-- <van-number-keyboard v-model="rechargeAmount" theme="custom" extra-key="." close-button-text="完成" :show="isKeyboard" @blur="isKeyboard = false" /> -->
    <van-popup v-model="checkOrder" :style="{ width: '60%' }">
      <div class="popup_div">
        <h2>请确定微信支付是否完成</h2>
        <div class="btn_success" @click="checkOrderAction">已完成支付</div>
        <div class="btn_fail"  @click="checkOrderAction">支付遇到问题，重新支付</div>
      </div>
    </van-popup>
  </div>
</template>
<script>
import { mapGetters } from 'vuex';
import wx from 'weixin-js-sdk';
export default {
  name: 'wallet',
  data () {
    return {
      checkOrder: false,
      isWxBrowser: '',
      openId: '',
      wxChatConfig: {},
      rechargeNo: '',
      isKeyboard: false,
      rechargeAmount: '',
      activeIndex: 0,
      minRechargeAmount: 0.01,
      maxRechargeAmount: 10000,
      payList: [{
        value: 'weonline',
        name: '微信在线付款'
      }
      // , {
      //   value: 'wechat',
      //   name: '微信转账付款'
      // }, {
      //   value: 'alipay',
      //   name: '支付宝转账付款'
      // }, {
      //   value: 'unionpay',
      //   name: '银行卡转账付款'
      // }
      ]
    };
  },
  mounted () {
  },
  created () {
    this.init();
    this.checkOrderShow();
    this.rechargeFirst();
  },
  computed: {
    ...mapGetters(['isCert'])
  },
  methods: {
    init() {
      let that = this;
      // window.navigator.userAgent属性包含了浏览器类型、版本、操作系统类型、浏览器引擎类型等信息，这个属性可以用来判断浏览器类型
      var ua = window.navigator.userAgent.toLowerCase();
      // 通过正则表达式匹配ua中是否含有MicroMessenger字符串
      if (ua.match(/MicroMessenger/i) === 'micromessenger') {
        that.isWxBrowser = true;
      } else {
        that.isWxBrowser = false;
      }
    },
    rechargeFirst () {
      let that = this;
      that.$API.user.rechargeFirst().then(res => {
        if (!res.code) {
          that.minRechargeAmount = res.data.minRechargeAmount;
          that.maxRechargeAmount = res.data.maxRechargeAmount;
          that.wxChatConfig.appid = res.data.appid; // appid返回
          if (that.isWxBrowser) {
            let code = that.$route.query.code; // 获取url参数code
            if (code) {
              that.getOpenId(code);
            } else {
              that.wxGetCode('123');
            }
          }
        }
      });
    },
    rechargeSecond () {
      if (!this.rechargeAmount) {
        this.$toast('请输入充值金额不能为空');
        return;
      }
      if (this.rechargeAmount < this.minRechargeAmount) {
        this.$toast('充值金额不能低于' + this.minRechargeAmount + '元');
        return;
      }
      if (this.rechargeAmount > this.maxRechargeAmount) {
        this.$toast('充值金额不能高于' + this.maxRechargeAmount);
        return;
      }
      if (this.activeIndex === 0) { // 选择了微信在线付款
        this.createOrder(this.activeIndex); // 先产生充值订单
        return;
      }
      this.$router.replace({ path: '/topup/order', query: { amount: this.rechargeAmount, type: this.activeIndex + 1 } });
    },
    wxGetCode(state) {
      let that = this;
      let APPID = that.wxChatConfig.appid;
      let SCOPE = 'snsapi_base';
      let REDIRECT_URI = that.$WEB_URL + '/topup'; // that.$WEB_URL+
      let pin_url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + APPID + '&redirect_uri=' + REDIRECT_URI + '&response_type=code&scope=' + SCOPE + '&state=' + state + '#wechat_redirect';
      window.location.href = pin_url;
    },
    createOrder(type) {
      let that = this;
      that.$API.user.rechargeSecond({
        amount: that.rechargeAmount,
        type: type + 4
      }).then(res => {
        console.log(res);
        if (!res.code) {
          that.rechargeNo = res.data.rechargeNo;
          localStorage.setItem('rechargeNo', that.rechargeNo);
        }
        if (that.isWxBrowser) {
          let token = localStorage.getItem('Token');
          that.$API.home.getPayParams({ no: that.rechargeNo, openid: that.openId, token: token }).then(res => {
            if (!res.code) {
              wx.ready(function() {
                wx.chooseWXPay({
                  appId: that.wxChatConfig.appId,
                  timestamp: res.timeStamp, // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
                  nonceStr: res.nonceStr, // 支付签名随机串，不长于32
                  package: res.prepay_id, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=\*\*\*）
                  signType: res.signType, // 签名方式，默认为'SHA1'，使用新版支付需传入'MD5'
                  paySign: res.paySign, // 支付签名
                  success: function (res) { // 跳转到支付成功页面有这个页面
                    that.$toast('支付成功');
                    console.log(res);
                    that.$router.push({ 'path': '/my' });
                  },
                  cancel: function (res) { // 提示引用的是mint-UI里toast
                    that.$toast('已取消支付');
                  },
                  fail: function (res) {
                    that.$toast('支付失败，请重试');
                  }
                });
              });
            }
          });
        } else { // 使用h5支付
          that.$API.home.getPayParams({ no: that.rechargeNo, tradeType: 'MWEB' }).then(res => {
            if (!res.code) {
              window.location.href = res.mweb_url;
            }
          });
        }
      });
    },
    checkOrderShow() {
      var that = this;
      let is_check = that.$route.query.is_check;
      if (is_check === '1' || is_check) {
        that.checkOrder = true;
      }
    },
    checkOrderAction() {
      var that = this;
      let rechargeNo = localStorage.getItem('rechargeNo');
      that.$API.home.checkOrderStatus({ outTradeNo: rechargeNo }).then(res => {
        that.checkOrder = false;
        if (!res.code) {
          this.$toast.success('支付成功');
        } else {
          this.$toast.fail('支付遇到问题，请重新支付');
        }
      });
    },
    getOpenId(code) { // 获得openId
      var that = this;
      var options = {};
      options.url = location.href.split('#')[0];
      options.code = code;
      that.$API.home.getOpenIdApi(options).then(res => {
        if (res.code !== 0) {
          that.wxGetCode('123');
          return;
        }
        let data = res.data;
        that.openId = data.openid;
        wx.config({
          debug: false, // 这里一般在测试阶段先用true，等打包给后台的时候就改回false,
          appId: data.js_appid,
          timestamp: data.js_timestamp,
          nonceStr: data.js_nonceStr,
          signature: data.js_signature,
          jsApiList: ['chooseWXPay']
        });
        wx.ready(function() {
          wx.checkJsApi({
            jsApiList: ['chooseWXPay'],
            success: function(res) {
              console.log('success');
              console.log(res);
            },
            fail: function(res) {
              console.log('fail');
              console.log(res);
            }
          });
        });
      });
    }
  }
};
</script>
<style lang="less" scoped>
.topup {
  height: 100%;
  background-color: #fff;
  .popup_div{
    text-align: center;
    h2{
      width:100%;
      padding:20px 0;
    }
    .btn_success{
      color:rgb(18, 93, 255);
      font-weight: bold;
      font-size: 30px;
      width:100%;
      border-top:1px solid #ccc;
      border-bottom:1px solid #ccc;
      padding:20px 0;
    }
    .btn_fail{
      padding:20px 0;
      font-weight: bold;
      font-size: 25px;
    }
  }
  .name {
    color: #353535;
    font-size: 28px;
    padding: 39px 42px;
  }
  .box {
    margin: 0 43px;
    display: flex;
    .symbol {
      padding: 10px 20px;
      color: #353535;
      font-size: 60px;
      text-align: center;
    }
    .input {
      flex: 1;
    }
  }
  .info {
    font-size: 26px;
    color: #ff0000;
    padding: 20px 20px 0 180px;
  }
  .line {
    height: 20px;
    background: rgba(241, 243, 247, 1);
    margin: 30px 0;
  }
  .payTitle {
    color: #353535;
    font-size: 28px;
    padding: 0 42px 20px;
  }
  .payList {
    padding: 0 40px;
    .rows-item {
      padding: 0 30px;
      border-bottom: 1px solid #eee;
      display: flex;
      justify-content: center;
      align-items: center;
      .radio {
        width: 32px;
        display: block;
        height: 32px;
        margin-right: 20px;
        display: flex;
        justify-content: center;
        align-items: center;
        background: rgba(255, 255, 255, 1);
        border-radius: 34px;
        background-image: url('/static/images/icon-topup-radio.png');
        background-repeat: no-repeat;
        background-size: contain;
      }
      .radio.active {
        background-image: url('/static/images/icon-topup-radio-active.png');
        &::before {
          content: '';
          margin: 4px;
          display: block;
          width: 20px;
          height: 20px;
          border-radius: 20px;
        }
      }
      .payName {
        flex: 1;
        display: flex;
        width: 100%;
        align-items: center;
        color: #353535;
        font-weight: 400;
        font-size: 27px;
        padding: 40px 0 40px;
        position: relative;
        &::before {
          content: '';
          display: block;
          background-repeat: no-repeat;
          background-size: cover;
          background-position: center center;
          margin: 0 20px;
        }
      }
      .wechat {
        &::before {
          width: 45px;
          height: 38px;
          background-image: url('/static/images/icon-topup-wechat.png');
        }
      }
      .alipay {
        &::before {
          width: 42px;
          height: 42px;
          background-image: url('/static/images/icon-topup-alipay.png');
        }
      }
      .unionpay {
        &::before {
          width: 49px;
          height: 30px;
          background-image: url('/static/images/icon-topup-unionpay.png');
        }
      }
    }
  }
  .submitAdd {
    padding: 30px 40px;
    color: #fff;
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    font-size: 32px;
    text-align: center;
    .btn {
      width: 100%;
    }
    .van-button__text {
      color: #fff;
      font-size: 32px;
    }
  }
}
</style>
